﻿
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using System.Reflection;
using TrackSystem.Contracts;
using TrackSystem.Entities.Models;
using TrackSystem.EntityFramework;

namespace TrackSystem.API.Extensions
{
    /// <summary>
    /// 控制器扩展功能定义类
    /// </summary>
    public static class ServiceExtensions
    {
        /// <summary>
        /// 跨域配置函数
        /// </summary>
        /// <param name="services">服务器</param>
        public static void ConfigureCors(this IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader());
            });
        }

        /// <summary>
        /// MySQL数据库上下文配置函数
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        public static void ConfigurationMySqlContext(this IServiceCollection services, IConfiguration config)
        {
            services.AddIdentity<User, IdentityRole>(options =>
            {
                // 密码设置
                options.Password.RequireDigit = false; // 需要数字
                options.Password.RequireLowercase = false; // 需要小写字母
                options.Password.RequireUppercase = false; // 需要大写字母
                options.Password.RequiredLength = 4; // 最小长度
                options.Password.RequireNonAlphanumeric = false; // 不需要非字母数字字符
                // 用户设置
                options.User.RequireUniqueEmail = false; // 需要唯一的电子邮件地址
                options.SignIn.RequireConfirmedEmail = true; // 需要确认电子邮件
                options.Tokens.EmailConfirmationTokenProvider = "EmailConfirmation"; // 使用电子邮件确认令牌提供程序
                // 锁定设置
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(3); // 默认锁定时间
                options.Lockout.MaxFailedAccessAttempts = 3; // 最大失败尝试次数
            })
            .AddErrorDescriber<CustomIdentityErrorDescriber>() // 自定义错误描述
            .AddEntityFrameworkStores<TkDBContent>()
            .AddDefaultTokenProviders() // 添加默认令牌提供程序
            .AddTokenProvider<EmailConfirmationTokenProvider<User>>("EmailConfirmation") // 添加电子邮件确认令牌提供程序
            ;

            services.Configure<DataProtectionTokenProviderOptions>(
                options => options.TokenLifespan = TimeSpan.FromHours(2)); // 设置令牌有效期为24小时

            // 配置电子邮件确认令牌提供程序选项
            services.Configure<EmailConfirmationTokenProviderOptions>(
                options => options.TokenLifespan = TimeSpan.FromHours(24)); // 设置令牌有效期为24小时

            // 配置数据库上下文
            var connectionString = config.GetConnectionString("PlatformDb");
            services.AddDbContext<TkDBContent>(builder =>
            {
                builder.UseMySql(connectionString, MySqlServerVersion.LatestSupportedServerVersion,
                    options => options.EnableRetryOnFailure());
            });
        }

        /// <summary>
        /// 注册仓储模式的服务
        /// </summary>
        /// <param name="services"></param>
        public static void ConfigureRepositoryWrapper(this IServiceCollection services)
        {
            services.AddScoped<IRepositoryWrapper, RepositoryWrapper>();
        }

        /// <summary>
        /// 配置Swagger,显示注释
        /// </summary>
        /// <param name="services"></param>
        public static void ConfigureSwagger(this IServiceCollection services)
        {
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "深海有缆装备控制系统",
                    Version = "v1"
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFile));
            });
        }
    }
}
